package com.sunlands.deskmate.message.handler.storager.interceptor.impl;

import com.sunlands.deskmate.message.entity.Messages;
import com.sunlands.deskmate.message.enums.MessageType;
import com.sunlands.deskmate.channel.WebSocketServerHandler;
import com.sunlands.deskmate.message.handler.storager.interceptor.Interceptor;
import com.sunlands.deskmate.service.DialogRecordServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import java.util.Set;

/**
 * 房间消息处理，用于维护房间会话中的人员信息
 */
@Order(10000)
@Slf4j
@Component
public class LiveRoomMessageInterceptor implements Interceptor {

    @Autowired
    private DialogRecordServiceImpl dialogRecordService;

    @Override
    public boolean interceptor(Messages msgEntity) {
        if (isLiveMessage(msgEntity)) {
            String key = WebSocketServerHandler.getRoomKey(msgEntity.getType(), msgEntity.getToId());
            if (MessageType.QUIT_ROOM.getType().equals(msgEntity.getType())) {
                Set<Long> roomUsers = dialogRecordService.refreshMembers(key);
                if (roomUsers != null) {
                    roomUsers.remove(Long.parseLong(msgEntity.getFromUserId()));
                    log.info("连麦房间用户集合-删除用户 userId = {} 之后的集合为 roomUsers = {}", msgEntity.getFromUserId(), roomUsers);
                }
            }
        }
        return true;
    }

    private boolean isLiveMessage(Messages msgEntity) {
        return msgEntity.getType().startsWith("3");
    }


}